﻿using Alternet.Scripter.Debugger;
using Alternet.Scripter;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Remoting.Channels;
using System.Threading.Channels;
using System.Runtime.Remoting;

namespace OrBitDataModule.ScripterDebugger
{
    public class RemoteControlService
    {
        private readonly RemoteControlParameters parameters;

        private IChannel channel;
        public RemoteControlService(RemoteControlParameters parameters)
        {
            this.parameters = parameters;

        }

        public void StartClient()
        {
            channel = null;
            RemoteControl = DebuggerCommunication.StartClient(out channel,
             parameters.IpcPortName,
             parameters.IpcObjectUri,
             parameters.IpcPortName != null ? parameters.IpcPortName + "ClientChannel" : null);
        }


        public void StopClient()
        {
            if (channel != null)
            {
                try
                {
                    DebuggerCommunication.StopClient(channel);
                    channel = null;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

            }
        }

        public IScriptDebuggerRemoteControl RemoteControl { get; set; }

        public void CompileScript(ScriptCompiledDelegate onScriptCompiled)
        {
            if (RemoteControl != null)
            {
                var sink = new DebuggerCommunication.ScriptDebuggerRemoteControlCompileCallbackSink(onScriptCompiled);

                RemoteControl.CompileScript(sink.OnScriptCompiled);
            }
        }

        public void StartScript(ScriptFinishedDelegate onScriptFinished)
        {
            if (RemoteControl != null)
            {
                var sink = new DebuggerCommunication.ScriptDebuggerRemoteControlStartCallbackSink(onScriptFinished);
                RemoteControl.StartScript(sink.OnScriptFinished);
            }
        }

        public void StopScript()
        {
            if (RemoteControl != null)
                RemoteControl.StopScript();
        }
    }
}
